package top.songxs.gmall.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.songxs.gmall.feign.order.OrderFeignClient;
import top.songxs.gmall.order.entity.OrderInfo;
import top.songxs.gmall.payment.properties.AlipayProperties;
import top.songxs.gmall.payment.service.PaymentService;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private AlipayProperties alipayProperties;
    @Autowired
    private OrderFeignClient orderFeignClient;

    @Override
    public String payMoney(Long orderId) {


        try {
            OrderInfo orderInfo = orderFeignClient.findById(orderId).getData();
            // TODO 调用支付宝支付接口，得到支付提交表单html数据，并进行返回
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
//            AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();



            alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
            alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());

            // 构建请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("out_trade_no", orderInfo.getOutTradeNo());
            params.put("total_amount", orderInfo.getTotalAmount().doubleValue());
            params.put("subject", orderInfo.getTradeBody());
            params.put("product_code", "FAST_INSTANT_TRADE_PAY");
            //传递订单支付的超时时间，过期自动收单

            String timeOutDate = DateFormatUtils.format(orderInfo.getExpireTime(),"yyyy-MM-dd HH:mm:ss");
            params.put("time_expire", timeOutDate);
            String bizContent = JSON.toJSONString(params);
            alipayRequest.setBizContent(bizContent);

            //请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println(result);
            return result;


        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }
}
